package com.platform.qujia.service.impl;

import com.platform.qujia.constantEnum.Constant;
import com.platform.qujia.constantEnum.DecimalConstant;
import com.platform.qujia.constantEnum.PayWayPayTypeEnum;
import com.platform.qujia.constantEnum.TianQuetechPayEnum;
import com.platform.qujia.dao.PayOrderMapper;
import com.platform.qujia.dao.PayWayMapper;
import com.platform.qujia.dao.StaOilGunMapper;
import com.platform.qujia.dao.StationMapper;
import com.platform.qujia.enums.PayWayServiceChargeEnum;
import com.platform.qujia.enums.PayWayUseTypeEnum;
import com.platform.qujia.handle.PayOrderHandle;
import com.platform.qujia.param.request.AddPayOrderParam;
import com.platform.qujia.param.request.PayOrderRequest;
import com.platform.qujia.param.request.TradeReverseScanPayParameter;
//import com.platform.qujia.param.response.YunhuaPayRes;
//import com.platform.qujia.param.response.YunhuaResponse;
import com.platform.qujia.pay.PayChannelHandler;
import com.platform.qujia.pay.PaymentStrategy;
import com.platform.qujia.pay.QueryOrderStrategy;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.ReductionAndCouponDTO;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.LocalDateTimeUtil;
import com.platform.qujia.utils.StringUtils;
import com.platform.qujia.utils.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @date 2023/8/10
 */
@Service
public class PaymentServiceImpl implements IPaymentService {

    private static final Logger log = LoggerFactory.getLogger(PaymentServiceImpl.class);

    public static final String POS_DEFAULT_PAY_TYPE = PayWayPayTypeEnum.Pay_Type_Accompanying_payment.getValue().toString();

    @Autowired
    private PayChannelHandler payChannelHandler;

    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private ReductionActivityService reductionActivityService;
    @Autowired
    private TradePaymentRecordsService tradePaymentRecordsService;
//    @Autowired
//    private EnterpriseService enterpriseService;
    @Autowired
    private StationMapper stationMapper;
    @Autowired
    private StaOilGunMapper staOilGunMapper;
    @Autowired
    private PayWayMapper payWayMapper;
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private AppUserInfoService appUserInfoService;

    @Override
    public TradeReversePayVO scanPay(AddPayOrderParam orderParam) {
        log.info("pos机扫码支付开始");
        // 根据apptype查找pos的支付渠道
        PayWay payWay = getStationPosPayWay(orderParam.getStationId());
        if (payWay==null) {
            log.error("找不到支付渠道，stationId:{}, 请求参数:{}",orderParam.getStationId(),orderParam);
            throw new CustomException("找不到支付渠道");
        }

        PayWayPayTypeEnum payTypeEnum = PayWayPayTypeEnum.getByValue(Integer.valueOf(payWay.getPayType()));
        PaymentStrategy strategy = payChannelHandler.getPaymentStrategy(payTypeEnum);

        orderParam.setMno(payWay.getMno());
        log.info("请求参数:{}",orderParam);

        // 获取油枪、油品信息
        StaOilGun oilGun = getOilGun(orderParam);

        //订单实付金额
        BigDecimal amt = new BigDecimal(orderParam.getAmt());
        AppUserInfo userInfo = null;
        if (StringUtils.isNotBlank(orderParam.getConsumerId())) {
            String consumerId = orderParam.getConsumerId();
            BigDecimal id = new BigDecimal(consumerId);
            userInfo = appUserInfoService.getById(id.intValue());
            if (userInfo == null) {
                throw new CustomException("会员未找到");
            }
        }

        PayOrder newPayOrder = new PayOrder();
        newPayOrder.setReceivableAmt(orderParam.getReceivableAmt()); // 应收金额
        newPayOrder.setAmt(amt.doubleValue());// 实收金额
        newPayOrder.setDiscountAmt(0d);// 优惠金额
        newPayOrder.setConsumeDiscountAmt(BigDecimal.ZERO);
        newPayOrder.setRechargeDiscountAmt(BigDecimal.ZERO);
        newPayOrder.setActivityId(null); // 设置立减活动id
        String orderNo=StringUtils.generateOrdNo();
        newPayOrder.setOrderNo(orderNo);//订单号
        Station station = stationMapper.selectStationById(orderParam.getStationId());
        newPayOrder.setEnterpriseId(orderParam.getEnterpriseId());
        newPayOrder.setEnterpriseName(station==null?null:station.getEnterprise().getEnterpriseName());
        newPayOrder.setAppType(orderParam.getAppType());
        newPayOrder.setPayType(orderParam.getPayType());
        newPayOrder.setOrderOriginType(orderParam.getOrderOriginType());
        newPayOrder.setStationName(station.getStationName());
        newPayOrder.setStationId(station.getStationId());                  //油站id
        newPayOrder.setStatus("0");                                                //创建订单 未支付状态 0
        newPayOrder.setCreatedDate(new Date());           //创建时间
        newPayOrder.setOilGun(orderParam.getOilGun());                        //油枪号
        newPayOrder.setDzkAmt(Double.valueOf(0));             //电子卡金额
        newPayOrder.setOilPirce(orderParam.getOilPirce()); //油价 原价
        newPayOrder.setOrderType(oilGun.getOil().getOilClass()); // 油品类
        newPayOrder.setOilName(oilGun.getOilId().toString()); // 油品id
        newPayOrder.setOilId(oilGun.getOil().getOilId());
        newPayOrder.setOrderLiters(orderParam.getOrderLiters()); // 油升数
        newPayOrder.setOilPersonnelId(orderParam.getOilPersonnelId());
        newPayOrder.setPayWayId(payWay.getPayWayId());
        newPayOrder.setUtmSource("9");// 订单来源默认9
        newPayOrder.setXJStatus("1");//现金支付的状态（0申请1取消）
        newPayOrder.setReceivedAmt(amt.doubleValue());
        if (userInfo != null) {
            newPayOrder.setCustomerPhone(userInfo.getMobilePhone());
            newPayOrder.setConsumerId(userInfo.getUserId());
            newPayOrder.setConsumer(userInfo.getBlogNickName());
        }
        PayOrderHandle.setPayOrderInvoiceStatus(newPayOrder);
        int i = payOrderMapper.insertSelectiveOrder(newPayOrder);  // 添加订单
        if (i<1) {
            throw new CustomException("创建订单失败");
        }
        BigDecimal originalAmt = amt;
        //优惠金额
        BigDecimal discountAmt = null;
        if (orderParam.getEnableDiscount()) {
            ReductionAndCouponDTO dto = reductionActivityService.calculateReductionDiscount(orderParam, newPayOrder, station, oilGun, userInfo);
            if (dto != null && dto.getActivityId() != null) {
                //优惠金额
                discountAmt = dto.getReductionAmt();
                amt = amt.subtract(discountAmt);
                if (amt.compareTo(DecimalConstant.O_01)<0) {
                    amt = DecimalConstant.O_01;
                    discountAmt = originalAmt.subtract(DecimalConstant.O_01);
                }
                newPayOrder.setActivityId(dto.getActivityId());
                newPayOrder.setAmt(amt.doubleValue());
                newPayOrder.setDiscountAmt(discountAmt.doubleValue());
                newPayOrder.setConsumeDiscountAmt(discountAmt);
            }
        }
        // 计算渠道费
        calculatorChannelFee(newPayOrder,payWay,amt);
        i = payOrderMapper.updateByPrimaryKeySelective(newPayOrder);
        if (i<1) {
            throw new CustomException("更新订单失败");
        }

        Object result = null;
        try{
            log.info("开始进行支付前置方法，渠道:{}",payTypeEnum.getKey());
            // 支付策略前置处理
            Object preParam = strategy.beforePay(orderParam,newPayOrder,payWay);
            log.info("调用第三方支付，渠道：{}",payTypeEnum.getKey());
            // 进行第三方支付调用
            orderParam.setPay(true);
            result = strategy.doPay(orderParam,newPayOrder,payWay,preParam);
            log.info("第三方支付后置处理，渠道：{}",payTypeEnum.getKey());
            strategy.postPay(newPayOrder,result);
            // 检查调用是否成功
            if (!strategy.checkResult2(newPayOrder,result)) {
                throw new CustomException("支付失败");
            }
        }catch (Exception e){
            log.info("调用第三方支付失败，渠道：{}",payTypeEnum.getKey());
            if(e instanceof CustomException){
                CustomException ce = (CustomException) e;
                if (ce.getCode() == CodeMsg.TRADE_REVERSE_PAY_WAIT_MINUTE.getRetCode()) {
                    // 支付中,应该单独返回一个状态
                    throw new CustomException("支付中",0);
                }else {
                    // 支付失败
                    if(orderParam.getEnableDiscount() && newPayOrder.getActivityId() != null && discountAmt != null){
                        // 回滚立减活动预算
                        reductionActivityService.updateReductionActivityBudget(discountAmt, Math.toIntExact(newPayOrder.getActivityId()));
                    }
                }
                throw e;
            }else{
                log.error(e.getMessage(),e);
                throw new CustomException("支付失败");
            }
        }
        log.info("调用第三方支付成功，渠道：{}",payTypeEnum.getKey());
//        PayOrder payOrderTemp=new PayOrder();
//        payOrderTemp.setOrderNo(newPayOrder.getOrderNo());
//        payOrderTemp.setReceivedAmt(newPayOrder.getAmt());
//        strategy.postPay(payOrderTemp,result);
//        payOrderService.updatePayOrder(payOrderTemp);
        // 扫码免密同步支付成功后策略执行一些操作
        strategy.syncPostPay(newPayOrder,result);
        TradeReversePayVO payvo=new TradeReversePayVO();
        payvo.setAmt(amt);
        payvo.setDiscountAmt(discountAmt==null?BigDecimal.ZERO:discountAmt);
        payvo.setTradeMsg("支付成功");
        payvo.setOrderNo(newPayOrder.getOrderNo());
        payvo.setPayType("POS机");
        return payvo;
    }

    /**
     * 兼容旧pos版本，现在pos都换成新版本了
     * @param orderParam
     * @return
     */
    @Override
    @Deprecated
    public TradeReversePayVO scanPay2(AddPayOrderParam orderParam) {
        log.info("pos机扫码支付开始");
        // 根据apptype查找pos的支付渠道
        PayWay payWay = getStationPosPayWay(orderParam.getStationId());
        if (payWay==null) {
            log.error("找不到支付渠道，stationId:{}, 请求参数:{}",orderParam.getStationId(),orderParam);
            throw new CustomException("找不到支付渠道");
        }

        PayWayPayTypeEnum payTypeEnum = PayWayPayTypeEnum.getByValue(Integer.valueOf(payWay.getPayType()));
        PaymentStrategy strategy = payChannelHandler.getPaymentStrategy(payTypeEnum);

        orderParam.setMno(payWay.getMno());
        log.info("请求参数:{}",orderParam);

        // 获取油枪、油品信息
        StaOilGun oilGun = getOilGun(orderParam);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //订单实付金额
        BigDecimal amt = new BigDecimal(orderParam.getAmt());
        BigDecimal originalAmt = amt;
        //参加的立减活动
        ReductionActivitiesVO activitiesVO = null;
        //优惠金额
        BigDecimal discountAmt = null;

        if (orderParam.getEnableDiscount()) {
            //订单立减活动优惠
            activitiesVO=new ReductionActivitiesVO();
            activitiesVO.setActivityUse("CSP");
            activitiesVO.setAmt(new BigDecimal(orderParam.getAmt()));
            activitiesVO.setDateTime(sdf.format(new Date()));
            activitiesVO.setEnterpriseId(orderParam.getEnterpriseId());
            activitiesVO.setOilId(oilGun.getOilId());
            activitiesVO.setOrderLiters(orderParam.getOrderLiters());
            activitiesVO.setStationId(orderParam.getStationId());
            activitiesVO.setPaymentMethod(orderParam.getPayType());
            // 抓不到用户信息的默认老用户
            activitiesVO.setMemberCategory(Constant.MEMBER_CATEGORY_OLD_USER);
            discountAmt=payOrderService.reductionActivitiesAmountCalculation(activitiesVO,null).setScale(2, BigDecimal.ROUND_HALF_UP);
            amt=amt.subtract(discountAmt);//计算参与活动之后的实付款金额
            if(amt.compareTo(BigDecimal.valueOf(0.01))<=0) {
                amt=BigDecimal.valueOf(0.01);
                discountAmt = originalAmt.subtract(amt);
            }
            if(activitiesVO.getActivityId()!=null) {
                //更新活动的预算，避免多个用户同时支付时，产生超预算的问题
                reductionActivityService.updateReductionActivityBudget(discountAmt.negate(), activitiesVO.getActivityId()==null?-1:activitiesVO.getActivityId());
            }
        }
        PayOrder newPayOrder = new PayOrder();
        newPayOrder.setReceivableAmt(orderParam.getReceivableAmt()); // 应收金额
        newPayOrder.setAmt(amt.doubleValue());// 实收金额
        newPayOrder.setDiscountAmt(discountAmt == null ? 0d : discountAmt.doubleValue());// 优惠金额
        newPayOrder.setActivityId( (activitiesVO !=null && activitiesVO.getActivityId() != null) ? Long.valueOf(activitiesVO.getActivityId()) : null); // 设置立减活动id
        // 计算渠道费
        calculatorChannelFee(newPayOrder,payWay,amt);
        String orderNo=StringUtils.generateOrdNo();
        newPayOrder.setOrderNo(orderNo);//订单号
        Station station = stationMapper.selectStationById(orderParam.getStationId());
        newPayOrder.setEnterpriseId(orderParam.getEnterpriseId());
        newPayOrder.setEnterpriseName(station==null?null:station.getEnterprise().getEnterpriseName());
        newPayOrder.setAppType(orderParam.getAppType());
        newPayOrder.setPayType(orderParam.getPayType());
        newPayOrder.setOrderOriginType(orderParam.getOrderOriginType());
        newPayOrder.setStationName(station.getStationName());
        newPayOrder.setStationId(station.getStationId());                  //油站id
        newPayOrder.setStatus("0");                                                //创建订单 未支付状态 0
        newPayOrder.setCreatedDate(new Date());           //创建时间
        newPayOrder.setOilGun(orderParam.getOilGun());                        //油枪号
        newPayOrder.setDzkAmt(Double.valueOf(0));             //电子卡金额
        newPayOrder.setOilPirce(orderParam.getOilPirce()); //油价 原价
        newPayOrder.setOrderType(oilGun.getOil().getOilClass()); // 油品类
        newPayOrder.setOilName(oilGun.getOilId().toString()); // 油品id
        newPayOrder.setOrderLiters(orderParam.getOrderLiters()); // 油升数
        newPayOrder.setOilPersonnelId(orderParam.getOilPersonnelId());
        newPayOrder.setPayWayId(payWay.getPayWayId());
        newPayOrder.setUtmSource("9");// 订单来源默认9
        newPayOrder.setXJStatus("1");//现金支付的状态（0申请1取消）
        newPayOrder.setReceivedAmt(amt.doubleValue());
        newPayOrder.setActualAmt(amt);
        Object result = null;
        try{
            PayOrderHandle.setPayOrderInvoiceStatus(newPayOrder);
            payOrderMapper.insertSelectiveOrder(newPayOrder);  // 添加订单
            log.info("开始进行支付前置方法，渠道:{}",payTypeEnum.getKey());
            // 支付策略前置处理
            Object preParam = strategy.beforePay(orderParam,newPayOrder,payWay);
            log.info("调用第三方支付，渠道：{}",payTypeEnum.getKey());
            // 进行第三方支付调用
            orderParam.setPay(true);
            result = strategy.doPay(orderParam,newPayOrder,payWay,preParam);
            log.info("第三方支付后置处理，渠道：{}",payTypeEnum.getKey());
            strategy.postPay(newPayOrder,result);
            // 检查调用是否成功
            if (!strategy.checkResult2(newPayOrder,result)) {
                throw new CustomException("支付失败");
            }
        }catch (Exception e){
            log.info("调用第三方支付失败，渠道：{}",payTypeEnum.getKey());
            boolean paying = e instanceof CustomException && (((CustomException) e).getCode() == CodeMsg.TRADE_REVERSE_PAY_WAIT_MINUTE.getRetCode());
            if (!paying) {
                if(orderParam.getEnableDiscount() && activitiesVO != null && discountAmt != null){
                    // 回滚立减活动预算
                    reductionActivityService.updateReductionActivityBudget(discountAmt, activitiesVO.getActivityId()==null?-1:activitiesVO.getActivityId());
                }
            }
            if(e instanceof CustomException){
                throw e;
            }else{
                log.error(e.getMessage(),e);
                throw new CustomException("支付失败");
            }
        }
        log.info("调用第三方支付成功，渠道：{}",payTypeEnum.getKey());
//        PayOrder payOrderTemp=new PayOrder();
//        payOrderTemp.setOrderNo(newPayOrder.getOrderNo());
//        payOrderTemp.setReceivedAmt(newPayOrder.getAmt());
//        strategy.postPay(payOrderTemp,result);
//        payOrderService.updatePayOrder(payOrderTemp);
        // 扫码免密同步支付成功后策略执行一些操作
        strategy.syncPostPay(newPayOrder,result);
        TradeReversePayVO payvo=new TradeReversePayVO();
        payvo.setAmt(amt);
        payvo.setDiscountAmt(discountAmt==null?BigDecimal.ZERO:discountAmt);
        payvo.setTradeMsg("支付成功");
        payvo.setOrderNo(newPayOrder.getOrderNo());
        payvo.setPayType("POS机");
        return payvo;
    }

    @Override
    public TradeReversePayVO queryOrder(TradeReverseScanPayParameter payParameter){

        String thirdPartyOrderNo = payParameter.getOrdNo();

        TradePaymentRecordsDO records=tradePaymentRecordsService.selectOneOrdNo(thirdPartyOrderNo);
        if(records==null) {
            throw new CustomException("支付失败,未查询到支付记录");
        }
        PayOrder newPayOrder =payOrderService.selectOrderInfoByOrdNo(records.getOrderSn());
        if(newPayOrder==null) {
            throw new CustomException("支付失败,未查询到订单");
        }

        if(StringUtils.equals("1",newPayOrder.getStatus())){
            TradeReversePayVO payvo=new TradeReversePayVO();
            payvo.setAmt(BigDecimal.valueOf(newPayOrder.getAmt()));
            payvo.setDiscountAmt(BigDecimal.valueOf(newPayOrder.getDiscountAmt()));
            payvo.setTradeMsg("支付成功");
            payvo.setOrderNo(newPayOrder.getOrderNo());
            payvo.setPayType("POS机");
            payvo.setOrder(newPayOrder);
            return payvo;
        }
        if(!StringUtils.equals("0",newPayOrder.getStatus())){
            throw  new CustomException("支付失败");
        }

        Integer payWayId = newPayOrder.getPayWayId();
        PayWay payWay = payWayMapper.selectPayWayById(Long.valueOf(payWayId));
        if (payWay == null) {
            throw new CustomException("找不到支付渠道");
        }

        PayWayPayTypeEnum typeEnum = PayWayPayTypeEnum.getByValue(Integer.valueOf(payWay.getPayType()));

        QueryOrderStrategy strategy = payChannelHandler.getQueryOrderStrategy(typeEnum);

        log.info("查询支付状态，{}",typeEnum.getKey());
        TianQuetechPayEnum orderStatus = strategy.getOrderStatus(payParameter,records,payWay);
        log.info("查询支付状态结束，{}",typeEnum.getKey());

//        if(orderStatus == TianQuetechPayEnum.PAY_SUCCESS){
//            TradeReversePayVO payvo=new TradeReversePayVO();
//            payvo.setAmt(BigDecimal.valueOf(newPayOrder.getAmt()));
//            payvo.setDiscountAmt(BigDecimal.valueOf(newPayOrder.getDiscountAmt()));
//            payvo.setTradeMsg("支付成功");
//            payvo.setOrderNo(newPayOrder.getOrderNo());
//            payvo.setPayType("POS机");
//            payvo.setOrder(newPayOrder);
//            return payvo;
//        }

        if(orderStatus == TianQuetechPayEnum.PAY_SUCCESS || orderStatus == TianQuetechPayEnum.PAY_PAYING){
            throw new CustomException(typeEnum.getKey()+"-支付中",CodeMsg.TRADE_REVERSE_PAY_WAIT_MINUTE.getRetCode());
        }

        if(orderStatus == TianQuetechPayEnum.PAY_FAIL){
            PayOrder updated = new PayOrder();
            updated.setOrderId(newPayOrder.getOrderId());
            updated.setStatus("4");
            payOrderService.updateByPrimaryKeySelective(updated);
            tradePaymentRecordsService.updateOrdNoStatus(thirdPartyOrderNo, TianQuetechPayEnum.PAY_FAIL.getValue());
            reductionActivityService.updateReductionActivityBudget(BigDecimal.valueOf(newPayOrder.getDiscountAmt()),
                    newPayOrder.getActivityId()==null?-1:newPayOrder.getActivityId().intValue());
            throw new CustomException(typeEnum.getKey()+"-支付失败");
        }
        throw new CustomException("支付失败");
    }

    @Override
    public PayWay getStationPosPayWay(Integer stationId) {
        PayWay payWayForm=new PayWay();
        payWayForm.setUseType(PayWayUseTypeEnum.CONSUME.getValue().toString());             //使用类型
        payWayForm.setStationId(stationId);
        payWayForm.setAppType(PayWayServiceChargeEnum.APPTYPE_POS.getValue().toString());
        PayWay payWay = payWayMapper.getOneStationPayWay(payWayForm); //获取该油站的支付类型

        if (payWay == null) {
            // 找不到查找随行付的
            payWayForm.setAppType(null);
            payWayForm.setPayType(POS_DEFAULT_PAY_TYPE);
            payWay = payWayMapper.getOneStationPayWay(payWayForm);
        }
        return payWay;
    }

    private StaOilGun getOilGun(AddPayOrderParam param){
        //油品价格
        StaOilGun queryOilGun = new StaOilGun();
        queryOilGun.setGunName(param.getOilGun());    // 枪号
        queryOilGun.setStationId(param.getStationId());//油站id
        StaOilGun staOilGun = staOilGunMapper.selectStaGunInfo(queryOilGun);
        if(staOilGun == null){
            throw new CustomException("创建订单失败，未找到油枪信息");
        }
        return staOilGun;
    }

    /*private void addPayOrder(PayOrder newPayOrder ,AddPayOrderParam param,StaOilGun staOilGun,PayWay payWay) {
        String orderNo=StringUtils.generateOrdNo();
        Station station = stationMapper.selectStationById(param.getStationId());

        newPayOrder.setEnterpriseId(param.getEnterpriseId());
        newPayOrder.setEnterpriseName(station==null?null:station.getEnterprise().getEnterpriseName());
        newPayOrder.setAppType(param.getAppType());
        newPayOrder.setPayType(param.getPayType());
        newPayOrder.setOrderOriginType(param.getOrderOriginType());
        newPayOrder.setStationName(param.getStationName());
        newPayOrder.setOrderNo(orderNo);                                          //订单号
        newPayOrder.setStationId(param.getStationId());                  //油站id
        newPayOrder.setStatus("0");                                                //创建订单 未支付状态 0
        newPayOrder.setCreatedDate(new Date());           //创建时间
        newPayOrder.setOilGun(param.getOilGun());                        //油枪号
        //newPayOrder.setReceivableAmt(Double.valueOf(param.getReceivableAmt()));      //订单应收金额
        newPayOrder.setDzkAmt(Double.valueOf(0));             //电子卡金额
        newPayOrder.setOilPirce(param.getOilPirce()); //油价 原价
        newPayOrder.setOrderType(staOilGun.getOil().getOilClass()); // 油品类
        newPayOrder.setOilName(staOilGun.getOilId().toString()); // 油品id
        //newPayOrder.setAmt(Double.valueOf(param.getReceivableAmt())); //实收金额
        //newPayOrder.setDiscountAmt(Double.valueOf("0.00")); //优惠金额
        newPayOrder.setOrderLiters(param.getOrderLiters()); // 油升数
        newPayOrder.setOilPersonnelId(param.getOilPersonnelId());
        newPayOrder.setPayWayId(payWay.getPayWayId());
        // 订单来源默认9
        newPayOrder.setUtmSource("9");

        //现金支付的状态（0申请1取消）
        newPayOrder.setXJStatus("1");
        payOrderMapper.insertSelectiveOrder(newPayOrder);
    }*/

    private void calculatorChannelFee(PayOrder payOrder,PayWay payWay,BigDecimal amt){
        BigDecimal serviceCharge;
        //费率,渠道手续费支付方 0司机/1油企 channelFeePayer
        if(StringUtils.equals(payWay.getAppType(),PayWayServiceChargeEnum.APPTYPE_POS.getValue().toString())){
            // 如果是pos应用渠道，费率按照配置的
            payOrder.setChannelFeePayer(payWay.getChannelFeePayer());
            serviceCharge = payWay.getServiceCharge();
        }else {
            // 如果不是，获取微信或支付宝费率
            Map<String,Object> map=getServiceChargew(payOrder.getStationId(),null);
            serviceCharge=map.get("serviceCharge")==null?BigDecimal.ZERO:new BigDecimal(map.get("serviceCharge").toString());
            payOrder.setChannelFeePayer("1");
        }
        payOrder.setServiceCharge(serviceCharge);
        // 渠道费
        if(amt.compareTo(DecimalConstant.O_01)<=0){
            payOrder.setActualAmt(amt);
            payOrder.setCommission(0d);
            return;
        }
        if (StringUtils.equals("1",payOrder.getChannelFeePayer())) {
            // 油企承担
            //渠道费
            BigDecimal commission = amt.multiply(serviceCharge).multiply(DecimalConstant.O_001).setScale(2, RoundingMode.HALF_UP);
            payOrder.setCommission(commission.doubleValue());
            payOrder.setActualAmt(amt);
        }else{
            // 司机承担
            // 司机承担的渠道费
            BigDecimal driverCommission = amt.multiply(serviceCharge).multiply(DecimalConstant.O_001).setScale(2, RoundingMode.HALF_UP);
            amt = amt.add(driverCommission).setScale(2,RoundingMode.HALF_UP);
            payOrder.setAmt(amt.doubleValue());
            payOrder.setActualAmt(amt);
            payOrder.setCommission(amt.multiply(serviceCharge).multiply(DecimalConstant.O_001).setScale(2,RoundingMode.HALF_UP).doubleValue());
        }
    }

    private Map<String,Object> getServiceChargew(Integer stationId,Integer appType) {
        Map<String,Object> map;
        if(appType!=null) {
            map=payOrderMapper.selectServiceCharge(stationId,appType);
            return map==null?new HashMap<>():map;
        }
        map=payOrderMapper.selectServiceCharge(stationId, PayWayServiceChargeEnum.APPTYPE_WECHAT.getValue());
        if(map == null || map.get("serviceCharge")==null) {
            map=payOrderMapper.selectServiceCharge(stationId,PayWayServiceChargeEnum.APPTYPE_ALIPAY.getValue());
        }
        return map==null?new HashMap<>():map;
    }

}
